<?php

namespace App\Trip\Orders\BookOrders\Params;

use App\Models\Train\Stations\Repositories\Interfaces\StationRepositoryInterface;
use App\Models\Train\Stations\TrainStation;
use App\Trip\Orders\BookOrders\Params\AbstractParam\TripParam;
use App\Trip\Train\TrainInfo\TrainInfo;
use Carbon\Carbon;
use Exception;

class TrainParam extends TripParam
{
    private array                      $train_param;
    private StationRepositoryInterface $stationRepo;

    public function __construct(array $params)
    {
        $this->train_param = $params;
        $this->stationRepo = app(StationRepositoryInterface::class);
    }

    /**
     * @throws Exception
     */
    public function toArray(): array
    {
        return $this->getTripInfo()->getTrainInfo();
    }

    /**
     * @throws Exception
     */
    public function getTripInfo(): TrainInfo
    {
        $train_info = new TrainInfo();
        $train_info->setDepartAt($this->getStartAt());
        $train_info->setArriveAt($this->getArriveAt());
        $train_info->setTrainCode($this->getTripCode());
        $train_info->setFromStationCode($this->getFromCode());
        $train_info->setToStationCode($this->getToCode());
        return $train_info;
    }

    public function getStartAt(): string
    {
        return Carbon::parse($this->start_at)->format('Y-m-d H:i');
    }

    public function getArriveAt(): string
    {
        return Carbon::parse($this->arrive_at)->format('Y-m-d H:i');
    }

    public function getTripCode(): string
    {
        return $this->train_code;
    }

    public function getFromCode(): string
    {
        return $this->from_code;
    }

    public function getToCode(): string
    {
        return $this->to_code;
    }

    public function getFromName(): string
    {
        return $this->from_name ?? $this->getFrom()->getStationName();
    }

    public function getFrom(): TrainStation
    {
        return $this->stationRepo->findOneByCode($this->getFromCode());
    }

    public function getToName(): string
    {
        return $this->to_name ?? $this->getTo()->getStationName();
    }

    public function getTo(): TrainStation
    {
        return $this->stationRepo->findOneByCode($this->getToCode());
    }

    public function getFromNameUy(): string
    {
        return $this->from_name_uy ?? $this->getFrom()->getStationNameUy();
    }

    public function getToNameUy(): string
    {
        return $this->to_name_uy ?? $this->getTo()->getStationNameUy();
    }

    public function __isset($name): bool
    {
        return isset($this->train_param[$name]);
    }

    /**
     * @throws Exception
     */
    public function __get($name)
    {
        if (isset($this->train_param[$name])) {
            return $this->train_param[$name];
        } else {
            throw new Exception("TrainParam 属性：{$name}不存在");
        }
    }


}